#!/usr/bin/env python
# coding:utf-8
__author__ = 'carey'
__date__ = '2017/7/25 上午10:15'

import requests, json, sys
from config.logs import log
from config.api_cnf import keys, urls


def search(key=u'白菜', num=1):

		"""
		菜谱搜索
		:param key: 查询的菜名
		:param num: 获取数量
		:return:
		"""

		url = urls()

		params = {
			'appkey': keys(),
			'keyword': key,
			'num': num,
		}

		try:
			r = requests.get(url=url['search'], params=params)
			data = json.loads(r.text)
		except Exception, e:
			log(e)

		if int(data['code']) == 10000:
			if int(data['result']['status']) == 0:
				return data['result']['result']
			else:
				info = {'function': sys._getframe().f_code.co_name, 'key': key, 'msg': data['result']['msg']}
				log(info)
				# log(data['result']['msg'])
		else:
			info = {'function': sys._getframe().f_code.co_name, 'key': key, 'msg': data['msg']}
			log(info)
			# log(data['msg'])


def detail(id=1):

		"""
		id查询
		:param id: 菜谱ID
		:return:
		"""

		url = urls()

		params = {
			'appkey': keys(),
			'id': id,
		}

		try:
			r = requests.get(url=url['detail'], params=params)
			data = json.loads(r.text)
		except Exception, e:
			log(e)

		if int(data['code']) == 10000:
			if int(data['result']['status']) == 0:
				tags = data['result']['result']['tag']
				tag = tags.split(',')
				data['result']['result']['tag'] = tag
				return data['result']['result']
			else:
				info = {'function': sys._getframe().f_code.co_name, 'id': id, 'msg': data['result']['msg']}
				log(info)
		else:
			info = {'function': sys._getframe().f_code.co_name, 'id': id, 'msg': data['msg']}
			log(info)


def recipe_class():

		"""
		获取菜谱分类
		"""

		url = urls()

		params = {
			'appkey': keys(),
		}

		try:
			r = requests.get(url=url['recipe_class'], params=params)
			data = json.loads(r.text)
		except Exception, e:
			log(e)

		if int(data['code']) == 10000:
			if int(data['result']['status']) == 0:
				return data['result']['result']
			else:
				info = {'function': sys._getframe().f_code.co_name, 'msg': data['result']['msg']}
				log(info)
		else:
			info = {'function': sys._getframe().f_code.co_name, 'msg': data['msg']}
			log(info)


def byclass(classid=1, start=0, num=10):

		"""
		根据分类查询
		:param classid: 分类ID
		:param start: 起始条数
		:param num: 获取数量
		:return:
		"""

		url = urls()

		params = {
			'appkey': keys(),
			'classid': classid,
			'start': start,
			'num': num,
		}

		try:
			r = requests.get(url=url['byclass'], params=params)
			data = json.loads(r.text)
		except Exception, e:
			log(e)

		if int(data['code']) == 10000:
			if int(data['result']['status']) == 0:
				return data['result']['result']
			else:
				info = {'function': sys._getframe().f_code.co_name, 'classid': classid, 'msg': data['result']['msg']}
				log(info)
		else:
			info = {'function': sys._getframe().f_code.co_name, 'classid': classid, 'msg': data['msg']}
			log(info)
